package clock;

import listener.TimeChangeEvent;
import listener.TimeChangeListener;
import java.lang.String;
import java.lang.Thread;
import java.util.Iterator;
import java.util.Vector;

public class Time implements Runnable {
	private final static int ME_WAIT_LONG_TIME = 100;
	
	protected int count;
	private int previous;
	private Thread thread;
	private Vector<TimeChangeListener> listeners;

	public Time(int time) {
		count = time;
		previous = time;
		listeners = new Vector<TimeChangeListener>();
		
		thread = new Thread(this);
		thread.start();
	}

	public void addTimeChangeListener(TimeChangeListener e) {
		if (listeners.contains(e))
			return;
		listeners.add(e);
	}

	public void removeTimeChangeListener(TimeChangeListener e) {
		if (!listeners.contains(e))
			return;
		listeners.remove(e);
	}
	
	public void removeTimeChangeListeners() {
		if (listeners != null)
			listeners.clear();
	}

	private void createEvent() {
		TimeChangeEvent e = new TimeChangeEvent(this);
		Iterator<TimeChangeListener> i = listeners.iterator();
		while (i.hasNext())
			i.next().timeChange(e);
	}

	public void run() {
		while (true) {
			if (previous != count) {
				previous = count;
				createEvent();
			} try {
				Thread.sleep(ME_WAIT_LONG_TIME);
			} catch (InterruptedException e) {
				System.err.println("The thread was interrupted.\n" + e);
			}
		}
	}

	public String toString() {
		return (count < 10) ? ("0" + Integer.toString(count)) : Integer.toString(count);
	}
}
